//==============================================================================
#include "CApp.h"

//==============================================================================
void CApp::OnEvent(SDL_Event* Event) {
    CEvent::OnEvent(Event);
}

void CApp::OnKeyDown(SDLKey sym, SDLMod mod, Uint16 unicode) {
	switch(sym) {
	case SDLK_UP:
		mKeyUp = true;
		break;
	case SDLK_DOWN:
		mKeyDown = true;
		break;
	case SDLK_LEFT:
		mKeyLeft = true;
		break;
	case SDLK_RIGHT:
		mKeyRight = true;
		break;
	case SDLK_ESCAPE:
		*mServoEnabled = false;
		SDL_Quit();
		exit(0);
	default:
		// ignore key
		return;
	}

	updateSteppers();
}

void CApp::updateSteppers() {
	if (mKeyUp && !mKeyDown && !mKeyLeft && !mKeyRight) {
		*mLeftTarget = (short)1;
		*mRightTarget = (short)1;
	} else if (mKeyUp && !mKeyDown && !mKeyLeft && mKeyRight) {
		*mLeftTarget = (short)1;
		*mRightTarget = (short)0;
	} else if (!mKeyUp && !mKeyDown && !mKeyLeft && mKeyRight) {
		*mLeftTarget = (short)1;
		*mRightTarget = (short)-1;
	} else if (!mKeyUp && mKeyDown && !mKeyLeft && mKeyRight) {
		*mLeftTarget = (short)-1;
		*mRightTarget = (short)0;
	} else if (!mKeyUp && mKeyDown && !mKeyLeft && !mKeyRight) {
		*mLeftTarget = (short)-1;
		*mRightTarget = (short)-1;
	} else if (!mKeyUp && mKeyDown && mKeyLeft && !mKeyRight) {
		*mLeftTarget = (short)0;
		*mRightTarget = (short)-1;
	} else if (!mKeyUp && !mKeyDown && mKeyLeft && !mKeyRight) {
		*mLeftTarget = (short)-1;
		*mRightTarget = (short)1;
	} else if (mKeyUp && !mKeyDown && mKeyLeft && !mKeyRight) {
		*mLeftTarget = (short)0;
		*mRightTarget = (short)1;
	} else {
		*mLeftTarget = (short)0;
		*mRightTarget = (short)0;
	}
}

void CApp::OnKeyUp(SDLKey sym, SDLMod mod, Uint16 unicode) {
	switch(sym) {
	case SDLK_UP:
		mKeyUp = false;
		break;
	case SDLK_DOWN:
		mKeyDown = false;
		break;
	case SDLK_LEFT:
		mKeyLeft = false;
		break;
	case SDLK_RIGHT:
		mKeyRight = false;
		break;
	default:
		// ignore key
		return;
	}

	updateSteppers();
}

void CApp::OnMouseMove(int mX, int mY, int relX, int relY, bool Left,bool Right,bool Middle) {
	if ((mX != 320) || (mY != 240)) {
		mServoPositionCached += relY;
		*mServoPosition = (unsigned short)mServoPositionCached;
		SDL_WarpMouse(320, 240);
	}
}

//==============================================================================
void CApp::OnExit() {
	Running = false;
}

//==============================================================================
